<template>
  <div class="search-container">
    <form action="/" class="search-form">
      <van-search
        v-model="searchText"
        show-action
        background="#3296fa"
        placeholder="请输入搜索关键词"
        @cancel="onCancel"
        @focus="isShow = false"
        @search="onSearch"
      />
    </form>
    <search-results v-if="isShow" :search-text="searchText"></search-results>
    <search-suggestion
      v-else-if="searchText"
      :search-text="searchText"
      @search="onSearch"
    ></search-suggestion>
    <search-history
      v-else
      :SearchHistories="SearchHistories"
      @clearAll="SearchHistories = []"
      @search="onSearch"
    ></search-history>
  </div>
</template>

<script>
// a.搜索功能项组件化
// (1)创建组件>>>导入组件>>>注册组件>>>使用组件
// b,按需显示三个纽件
// (1)如果有搜索结果,优先显示搜索结果组件
// 2)如果没有搜索结果,看有没有搜索文本,有则显示搜索建议组件
// 3)都没有,就展示搜索历史组件
// (4)补充: 当搜索框获取焦点时,关闭搜索结果显示1
// .获取搜索建议
// (1)搜索建议于组件需要根据搜索文本来请求数据,先用父传于把搜索词传进去
// (2)利用watch监听输入框内容改变
// 3)封装接口>>>导入接口>>>定义请求方法>>>调用方法,获取数据>>>保存数据>>>渲染数据
import SearchHistory from './components/search-history.vue'
import SearchResults from './components/search-results.vue'
import SearchSuggestion from './components/search-suggestion.vue'
import { setItem, getItem } from '@/utils/storage'
export default {
  name: '',
  components: { SearchSuggestion, SearchResults, SearchHistory },
  props: {},
  data() {
    return {
      searchText: '',
      isShow: false,
      SearchHistories: getItem('SEARCH_HISTORY') || []
    }
  },
  computed: {},
  watch: {
    SearchHistories() {
      setItem('SEARCH_HISTORY', this.SearchHistories)
    }
  },
  created() {},
  mounted() {},
  methods: {
    onSearch(val) {
      this.searchText = val
      this.isShow = true
      const index = this.SearchHistories.indexOf(val)
      if (index !== -1) {
        this.SearchHistories.splice(index, 1)
      }
      this.SearchHistories.unshift(val)
    },
    onCancel() {
      this.$router.back()
    }
  }
}
</script>

<style lang="less" scoped>
.search-container {
  padding-top: 108px;
  .van-search__action {
    color: #fff;
  }
  .search-form {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1;
  }
}
</style>
